package com.jjx.utils;


import lombok.SneakyThrows;
import org.apache.commons.codec.binary.Base64;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Utils  implements PasswordEncoder{
	/**
	 * 加密
	 * @param rawPassword
	 * @return
	 */
	@SneakyThrows
	public  String encode(CharSequence rawPassword) {
		return MD6(rawPassword);
	}

	/**
	 * 解密 第一个参数是要匹配的密码，第二个参数是加密后的encode密文
	 * @param rawPassword 要匹配的密码
	 * @param encodedPassword 加密后的encode密文
	 * @return
	 */
	@SneakyThrows
	public  boolean matches(CharSequence rawPassword, String encodedPassword) {
		if (MD6(rawPassword).equals(encodedPassword)){
			return true;
		}
		return false;
	}

	public  String MD5(CharSequence rawPassword) throws NoSuchAlgorithmException {
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		String newstr = Base64.encodeBase64String(md5.digest(rawPassword.toString().getBytes()));
		return newstr;
	}

	/**
	 * 16位加密算法
	 * @param rawPassword
	 * @return
	 * @throws NoSuchAlgorithmException
	 */
	public  String MD6(CharSequence rawPassword) throws NoSuchAlgorithmException {
		char hexDigits[] = {
				'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
		};
		try {
			byte[] btInput = ((String)rawPassword).getBytes();
			// 获得MD5摘要算法的 MessageDigest 对象
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			// 使用指定的字节更新摘要
			mdInst.update(btInput);
			// 获得密文
			byte[] md = mdInst.digest();
			// 把密文转换成十六进制的字符串形式
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			return null;
		}
	}

}
